//
//  YKCommetnViewController.m
//  baisi
//
//  Created by 吴高烽 on 16/10/17.
//  Copyright © 2016年 吴高烽. All rights reserved.
//

#import "YKCommetnViewController.h"
#import "YKTopicCell.h"
#import <MJRefresh.h>
#import "YKComment.h"
#import "YKCommentCell.h"
#import "YKCommentHeaderView.h"
#import <AFNetworking.h>
static NSString * const YKCommentId = @"comment";

@interface YKCommetnViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
///工具条底部间距
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpace;
/** 最热评论 */
@property (nonatomic, strong) NSArray *hotComments;
/** 最新评论 */
@property (nonatomic, strong) NSMutableArray *latestComments;
/** 保存帖子的top_cmt */
@property (nonatomic, strong) YKComment *saved_top_cmt;
/** 保存当前的页码 */
@property (nonatomic, assign) NSInteger page;
/** 管理者 */
@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation YKCommetnViewController
-(AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager ;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNav];
    [self setupHeader];
    [self setupRefresh];
}
-(void)setupNav{
    self.navigationItem.title = @"评论";
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setImage:[UIImage imageNamed:@"comment_nav_item_share_icon"] forState:UIControlStateNormal];
    [rightBtn setImage:[UIImage imageNamed:@"comment_nav_item_share_icon_click"] forState:UIControlStateHighlighted];
    [rightBtn sizeToFit];
#warning button的响应事件
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    
//    self.navigationItem.rightBarButtonItem = [UIBarButtonItem  itemWithImage:<#(NSString *)#> selectImage:<#(NSString *)#> target:<#(id)#> action:<#(SEL)#>]
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    self.tableView.estimatedRowHeight = 74;
    self.tableView.rowHeight = UITableViewAutomaticDimension ;
    self.tableView.backgroundColor = YKGlobalBackgroundColor ;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YKCommentCell class]) bundle:nil] forCellReuseIdentifier:YKCommentId];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, YKTopictCellMargin, 0);
    YKLog(@"%@",self.topic.mj_keyValues);
}
-(void)setupHeader{
    UIView *header = [[UIView alloc]init];
    YKTopicCell *cell = [YKTopicCell cell];
    cell.topic = self.topic;
    cell.size = CGSizeMake(SCWidth, self.topic.cellHeight);
    [header addSubview:cell];
    header.height = self.topic.cellHeight ;
    self.tableView.tableHeaderView = header ;
    // cell的高度设置
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    // 背景色
    self.tableView.backgroundColor = YKGlobalBackgroundColor;
    
    // 注册
 //   [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([XMGCommentCell class]) bundle:nil] forCellReuseIdentifier:XMGCommentId];
    
    // 去掉分割线
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 内边距
//    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, YKTopictCellMargin, 0);
    //[self.tableView rig]
}
- (void)setupRefresh
{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewComments)];
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreComments)];
    self.tableView.mj_footer.hidden = YES ;
}
- (void)loadNewComments
{
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    // 参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"dataList";
    params[@"c"] = @"comment";
    params[@"data_id"] = self.topic.id;
    params[@"hot"] = @"1";
    
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        if (![responseObject isKindOfClass:[NSDictionary class]]) {
            [self.tableView.mj_header endRefreshing];
            return  ;
        }
//        YKLog(@"json==%@",[responseObject mj_JSONString]);
        // 最热评论
        self.hotComments = [YKComment mj_objectArrayWithKeyValuesArray:responseObject[@"hot"]];
        
        // 最新评论
        self.latestComments = [YKComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
//        页码
        self.page = 1 ;
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        NSInteger total = [responseObject[@"total"] integerValue];
        if (self.latestComments.count >= total) {
            self.tableView.mj_footer.hidden = YES;
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
}
-(void)loadMoreComments{
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    NSInteger page = self.page + 1 ;
    // 参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"dataList";
    params[@"c"] = @"comment";
    params[@"data_id"] = self.topic.id;
//    params[@"hot"] = @"1";
    params[@"page"] = @(page);
    YKComment *cmt = [self.latestComments lastObject];
    params[@"lastcid"] = cmt.id;
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
//        YKLog(@"json==%@",[responseObject mj_JSONString]);
        NSArray *newComments = [YKComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
//        YKLog(@"count = %zd",newComments.count);
        [self.latestComments addObjectsFromArray:newComments];
        //        页码
        self.page = page ;
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        NSInteger total = [responseObject[@"total"] integerValue];
        if (self.latestComments.count >= total) {
            self.tableView.mj_footer.hidden = YES;
        }else{
//            结束刷新状态
            [self.tableView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
}
/**
 * 返回第section组的所有评论数组
 */
- (NSArray *)commentsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.hotComments.count ? self.hotComments : self.latestComments;
    }
    return self.latestComments;
}

- (YKComment *)commentInIndexPath:(NSIndexPath *)indexPath
{
    return [self commentsInSection:indexPath.section][indexPath.row];
}
-(void)keyboardWillChangeFrame:(NSNotification*)noti{
//    YKLog(@"%@",noti);
    CGRect frame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.bottomSpace.constant = SCHeight - frame.origin.y ;
    CGFloat duration = [noti.userInfo[UIKeyboardAnimationCurveUserInfoKey]doubleValue];
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - <UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger hotCount = self.hotComments.count;
    NSInteger latestCount = self.latestComments.count;
    
    if (hotCount) return 2; // 有"最热评论" + "最新评论" 2组
    if (latestCount) return 1; // 有"最新评论" 1 组
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger hotCount = self.hotComments.count;
    NSInteger latestCount = self.latestComments.count;
    // 隐藏尾部控件
    tableView.mj_footer.hidden = (latestCount == 0);
    if (section == 0) {
        return hotCount ? hotCount : latestCount;
    }
    // 非第0组
    return latestCount;
}
///  heightForHeaderInSection   需要配合该方法一起使用
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   YKCommentHeaderView *header = [YKCommentHeaderView headerViewWithTableView:tableView];
    NSInteger hotCount = self.hotComments.count;

    // 设置label的数据
    if (section == 0) {
        header.title = hotCount ? @"最热评论" : @"最新评论";
    } else {
        header.title = @"最新评论";
    }
    return header ;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

/*
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSInteger hotCount = self.hotComments.count;
    if (section == 0) {
        return hotCount ? @"最热评论" : @"最新评论";
    }
    return @"最新评论";
}*/
/*
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
    return button ;

}
*/

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YKCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:YKCommentId];
    YKComment *comment = [self commentInIndexPath:indexPath];
    cell.comment = comment ;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    UIMenuController *menu = [UIMenuController sharedMenuController];
    if (menu.isMenuVisible) {
        [menu setMenuVisible:NO animated:YES];
    }else{
        YKCommentCell *cell = (YKCommentCell*)[tableView cellForRowAtIndexPath:indexPath];
        [cell becomeFirstResponder];

        UIMenuItem *ding = [[UIMenuItem alloc]initWithTitle:@"顶" action:@selector(ding:)];
        UIMenuItem *replay = [[UIMenuItem alloc]initWithTitle:@"回复" action:@selector(replay:)];
        UIMenuItem *report = [[UIMenuItem alloc]initWithTitle:@"举报" action:@selector(report:)];
        menu.menuItems = @[ding,replay,report];
        CGRect rect = CGRectMake(0, 0.5 * cell.height, cell.width, cell.height * 0.5 );
        [menu setTargetRect:rect inView:cell];
        [menu setMenuVisible:YES animated:YES];
    }
}
#pragma mark- MenuItem处理
-(void)ding:(UIMenuController*)menu{
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    NSLog(@"%s %@",__func__ ,[self commentInIndexPath:indexPath]);
}
-(void)replay:(UIMenuController*)menu{
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    NSLog(@"%s %@",__func__ ,[self commentInIndexPath:indexPath]);
}
-(void)report:(UIMenuController*)menu{
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    NSLog(@"%s %@",__func__ ,[self commentInIndexPath:indexPath]);
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
